package com.hanqi.util.shiro;

import com.hanqi.util.R;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomUserFilter extends UserFilter {

    /**
     * 未登录操作
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        if (isAjaxRequest(req)) {
            res.setContentType("application/json; charset=utf-8");
            res.getWriter().print(R.msg(-5));
        } else {
            super.redirectToLogin(request, response);
        }
    }

    /**
     * 是否是Ajax请求
     *
     * @param
     * @return
     * @throws
     * @Description:
     * @author pengbin <pengbin>
     * 2018/11/26 10:58
     */
    private static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        return requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest");
    }
}